#!/usr/bin/python3
import os
import random
import subprocess
import sys
import platform
import concurrent.futures
import threading


# 执行命令行程序
def executeCmd(cmd_list: list, output_file: list):
    # os.system(cmd_str)
    for cmd_str in cmd_list:
        print(cmd_str,output_file)
        # if platform.system() == 'Windows':
        #
        #     process = subprocess.run(cmd_str, stdout=output_file, stderr=subprocess.PIPE, text=True)
        # elif platform.system() == 'Linux':
        #     # os.system(cmd_str)
        #     process = subprocess.run(cmd_str, stdout=output_file, stderr=subprocess.PIPE, text=True,
        #                              shell=True)
        # else:
        #     print('Error!!!')


# sample_path 要测试的算例的目录
def batchTest(sample_path: str, thread_count : int,runTime: int, times:int, coarsen_limit: int):
    # 获取程序path

    exe_path = os.path.join("..", "runtime", "mcgpp.exe" if platform.system() == 'Windows' else "mcgpp")
    # 读取所有算例名字
    test_case = []
    with open(sample_path, 'r') as rf:
        lines = rf.readlines()
        for line in lines:
            line_list = []
            line = line.strip()
            test_case.append(line.split(' '))
    # 创建任务队列
    task_queue = []
    for mqi_no,line_list in enumerate(test_case):
        task = []
        instance_name = line_list[0]#算例名字
        seed_list = random.sample(range(1, 100000000), times)
        mqi_file = os.path.join("..", "MQI_BKV", instance_name, instance_name + "_result_" + str(mqi_no) + ".smat")
        for seed in seed_list:
            cmd_str = f'{exe_path} {instance_name}  {mqi_file} {str(seed)} {str(runTime)} {coarsen_limit}'
            output_file = instance_name + "_" + str(seed) + "_" + str(mqi_no)
            task.append(cmd_str,output_file)
        task_queue.append(task)

    # 创建线程池
    with concurrent.futures.ThreadPoolExecutor(max_workers=thread_count) as executor:
        # 提交任务到线程池
        for task in task_queue:
            cmd_str = task[0]
            output_file = task[1]
            executor.submit(executeCmd, cmd_str,output_file)
        # 等待所有任务完成
        executor.shutdown()
        print("over!")

#python3 ./case.txt 5 3600 10 60000
if __name__ == '__main__':
    sample_path = sys.argv[1]
    thread_count = int(sys.argv[2])
    run_time = int(sys.argv[3])
    times = int(sys.argv[4])
    coarsen_limit = int(sys.argv[5])
    print("算例输入文件:",sample_path,
          "线程数目:",thread_count,
          "运行时间:",run_time,
          "单个算例运行次数:",times,
          "缩合阈值:",coarsen_limit)
    batchTest(sample_path, thread_count,run_time,times, coarsen_limit)
